package com.tengju.bff.interfaces.covercharge.controller.provider;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.google.common.collect.Lists;
import com.idanchuang.component.base.JsonResult;
import com.tengju.bff.interfaces.covercharge.constant.ContractStatusEnum;
import com.tengju.bff.interfaces.covercharge.constant.CoverChargeErrorCode;
import com.tengju.bff.interfaces.covercharge.dto.SignContractInfo;
import com.tengju.bff.interfaces.covercharge.dto.SignContractQuery;
import com.tengju.bff.interfaces.covercharge.dto.SignSucContractInfo;
import com.tengju.bff.interfaces.covercharge.dto.SignSucContractQuery;
import com.tengju.bff.interfaces.covercharge.entity.po.ServiceContract;
import com.tengju.bff.interfaces.covercharge.entity.po.ServiceContractRelation;
import com.tengju.bff.interfaces.covercharge.handler.CoverChargeException;
import com.tengju.bff.interfaces.covercharge.intf.IContractProvider;
import com.tengju.bff.interfaces.covercharge.mapper.ServiceContractMapper;
import com.tengju.bff.interfaces.covercharge.mapper.ServiceContractRelationMapper;
import com.tengju.bff.interfaces.covercharge.service.bestsign.impl.contract.BestSignContractService;
import com.tengju.bff.interfaces.covercharge.util.DateTimeUtils;
import com.tengju.bff.interfaces.covercharge.util.UserUtils;
import com.tengju.bff.interfaces.shared.ApiResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Objects;

/**
 * @author liang_shi
 * @date 2020/8/19 16:51
 * @description 合同相关api提供服务
 */
@Slf4j
@Service("contractProvider")
public class ContractProvider implements IContractProvider {

    @Autowired
    private BestSignContractService bestSignContractService;

    @Autowired
    private ServiceContractRelationMapper contractRelationMapper;

    @Autowired
    private ServiceContractMapper contractMapper;


    @Override
    public ApiResponse<List<SignContractInfo>> querySignContract(@RequestBody SignContractQuery query) {
        log.info("查询用户签署的合同开始,请求:{}", query);
        if (Objects.isNull(query.getUserId())) {
            return ApiResponse.newFailure(CoverChargeErrorCode.PARAM_ERROR.getCode(), "用户id不能为空");
        }
        ServiceContractRelation relation = new ServiceContractRelation();
        relation.setIdCode(UserUtils.getIdCode(query.getUserId().intValue()));
        relation.setPlatformCode(query.getPlatformCode());
        relation.setUserFrom(query.getUserFrom());
        List<ServiceContractRelation> scrList = contractRelationMapper.selectList(new QueryWrapper<>(relation));
        List<SignContractInfo> result = Lists.newArrayList();
        if (CollectionUtils.isEmpty(scrList)) {
            log.info("查询用户签署的合同结束，结果为空");
            return ApiResponse.newSuccess(result);
        }
        for (ServiceContractRelation scr : scrList) {
            ServiceContract contract = new ServiceContract();
            contract.setContractId(scr.getContractId());
            contract.setStatus(query.getStatus());
            ServiceContract sc = contractMapper.selectOne(new QueryWrapper<>(contract));
            if (Objects.isNull(sc)) {
                continue;
            }
            SignContractInfo sci = new SignContractInfo();
            sci.setUserId(query.getUserId());
            sci.setPlatformCode(scr.getPlatformCode());
            sci.setUserFrom(scr.getUserFrom());
            sci.setSponsor(scr.getSponsor());
            sci.setAccount(scr.getAccount());
            sci.setContractId(scr.getContractId());
            sci.setTitle(sc.getTitle());

            sci.setSendTime(DateTimeUtils.parseDateAsString(sc.getSendTime(), DateTimeUtils.DEFAULT_DATE_TIME_FORMAT));
            sci.setFinishTime(DateTimeUtils.parseDateAsString(sc.getFinishTime(), DateTimeUtils.DEFAULT_DATE_TIME_FORMAT));
            sci.setSignExpireTime(DateTimeUtils.parseDateAsString(scr.getSignExpireTime(), DateTimeUtils.DEFAULT_DATE_TIME_FORMAT));

            sci.setBeginDate(DateTimeUtils.parseDateAsString(sc.getBeginDate(), DateTimeUtils.DATE_FORMAT));
            sci.setExpireDate(DateTimeUtils.parseDateAsString(sc.getExpireDate(), DateTimeUtils.DATE_FORMAT));

            sci.setSigners(sc.getSigners());
            sci.setStatus(sc.getStatus());
            result.add(sci);
        }
        log.info("查询用户签署的合同结束，结果:{}", result);
        return ApiResponse.newSuccess(result);
    }


    @Override
    public ApiResponse<SignSucContractInfo> querySucSignContract(@RequestBody SignSucContractQuery query) {
        log.info("查询用户签署成功的合同开始,请求:{}", query);
        if (Objects.isNull(query.getUserId())) {
            return ApiResponse.newFailure(CoverChargeErrorCode.PARAM_ERROR.getCode(), "用户id不能为空");
        }
        if (StringUtils.isBlank(query.getPlatformCode())) {
            return ApiResponse.newFailure(CoverChargeErrorCode.PARAM_ERROR.getCode(), "平台编号不能为空");
        }
        ServiceContractRelation relation = new ServiceContractRelation();
        relation.setIdCode(UserUtils.getIdCode(query.getUserId().intValue()));
        relation.setPlatformCode(query.getPlatformCode());
        //按签署时间倒序排序
        List<ServiceContractRelation> scrList = contractRelationMapper.selectList(new QueryWrapper<>(relation)
                .orderByDesc("create_time"));
        if (CollectionUtils.isEmpty(scrList)) {
            log.info("查询用户签署成功的合同结束,无签署信息");
            return ApiResponse.newSuccess(null);
        }
        SignSucContractInfo contractInfo = new SignSucContractInfo();
        for (ServiceContractRelation contractRelation : scrList) {
            QueryWrapper<ServiceContract> queryWrapper = new QueryWrapper<ServiceContract>()
                    .eq("contract_id", contractRelation.getContractId())
                    .eq("status", ContractStatusEnum.SUCCESS.getStatus());
            ServiceContract contract = contractMapper.selectOne(queryWrapper);
            //取签署成功的合同信息
            if (!Objects.isNull(contract)) {
                contractInfo.setContractId(contract.getContractId());
                break;
            }
        }
        log.info("查询用户签署成功的合同结束,结果:{}", contractInfo);
        return ApiResponse.newSuccess(contractInfo);
    }


    @Override
    public ApiResponse<String> queryContractPreviewUrl(@PathVariable("account") String account, @PathVariable("contractId") String contractId) {
        log.info("查询合同预览地址开始,请求:{}", contractId);
        String transId = String.valueOf(IdWorker.getId());
        try {
            String previewUrl = bestSignContractService.getContractPreviewUrl(transId, contractId, account);
            log.info("查询合同预览地址结束,结果:transId,{},{}", transId, previewUrl);
            return ApiResponse.newSuccess(previewUrl);
        } catch (CoverChargeException e) {
            return ApiResponse.newFailure(CoverChargeErrorCode.BUSINESS_ERROR.getCode(), e.getMsg());
        }
    }

    @Override
    public ApiResponse<byte[]> download(@PathVariable("contractId") String contractId) {
        log.info("下载合同文件开始,请求:{}", contractId);
        String transId = String.valueOf(IdWorker.getId());
        try {
            byte[] contractByte = bestSignContractService.contractDownload(transId, contractId);
            log.info("下载合同文件结束,transId:{}", transId);
            return ApiResponse.newSuccess(contractByte);
        } catch (CoverChargeException e) {
            return ApiResponse.newFailure(CoverChargeErrorCode.BUSINESS_ERROR.getCode(), e.getMsg());
        }
    }

}
